import mysql from 'mysql2/promise';
import { config } from '@/config';
import { logger } from '@/utils/logger';

/**
 * MySQL 连接池配置
 */
const mysqlConfig = {
  host: config.database.mysql.host,
  port: config.database.mysql.port,
  user: config.database.mysql.username,
  password: config.database.mysql.password,
  database: config.database.mysql.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  charset: 'utf8mb4',
};

/**
 * 创建 MySQL 连接池
 */
export const mysqlPool = mysql.createPool(mysqlConfig);

/**
 * 测试 MySQL 连接
 */
export const testMysqlConnection = async (): Promise<boolean> => {
  try {
    const connection = await mysqlPool.getConnection();
    await connection.ping();
    connection.release();
    logger.info('MySQL 数据库连接成功');
    return true;
  } catch (error) {
    logger.error('MySQL 数据库连接失败:', error);
    return false;
  }
};

/**
 * 执行 MySQL 查询
 */
export const executeQuery = async (
  query: string,
  params?: unknown[]
): Promise<unknown> => {
  try {
    const [results] = await mysqlPool.execute(query, params);
    return results;
  } catch (error) {
    logger.error('MySQL 查询执行失败:', error);
    throw error;
  }
};

/**
 * 执行事务
 */
export const executeTransaction = async (
  queries: Array<{ query: string; params?: unknown[] }>
): Promise<unknown[]> => {
  const connection = await mysqlPool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    const results: unknown[] = [];
    for (const { query, params } of queries) {
      const [result] = await connection.execute(query, params);
      results.push(result);
    }
    
    await connection.commit();
    return results;
  } catch (error) {
    await connection.rollback();
    logger.error('MySQL 事务执行失败:', error);
    throw error;
  } finally {
    connection.release();
  }
};

/**
 * 关闭 MySQL 连接池
 */
export const closeMysqlConnection = async (): Promise<void> => {
  try {
    await mysqlPool.end();
    logger.info('MySQL 连接池已关闭');
  } catch (error) {
    logger.error('关闭 MySQL 连接池失败:', error);
  }
};

export default mysqlPool;